package com.example.bookkeep.login;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bookkeep.R;
import com.example.bookkeep.Utils.OkHttpUtil;
import com.example.bookkeep.Utils.URLUtils;
import org.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    private EditText etUsername, etRealname, etPassword, etConfirmPassword ,etEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etUsername = findViewById(R.id.etRegisterUsername);
        etRealname = findViewById(R.id.etRealname);
        etPassword = findViewById(R.id.etRegisterPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        etEmail = findViewById(R.id.etEmail);

        Button btnRegister = findViewById(R.id.btnRegisterSubmit);

        btnRegister.setOnClickListener(v -> {
            String username = etUsername.getText().toString().trim();
            String realname = etRealname.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            String confirmPassword = etConfirmPassword.getText().toString().trim();
            String email = etEmail.getText().toString().trim();


            if (username.isEmpty() || realname.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()  || email.isEmpty()) {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!password.equals(confirmPassword)) {
                Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }

            new Thread(() -> {
                try {
                    JSONObject json = new JSONObject();
                    json.put("username", username);
                    json.put("password", password);
                    json.put("newPassword", password); // 与 password 相同
                    json.put("realname", realname);
                    json.put("email", email);

                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    RequestBody body = RequestBody.create(json.toString(), JSON);

                    Request request = new Request.Builder()
                            .url(URLUtils.BASE_URL + "/user")
                            .post(body)
                            .build();

                    OkHttpClient client = OkHttpUtil.getInstance();
                    Response response = client.newCall(request).execute();

                    if (response.isSuccessful()) {
                        String responseBody = response.body().string();
                        JSONObject result = new JSONObject(responseBody);
                        int code = result.getInt("code");
                        String message = result.getString("message");

                        runOnUiThread(() -> {
                            if (code == 1) {
                                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                                finish(); // 返回登录页面
                            } else {
                                Toast.makeText(this, "注册失败：" + message, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(this, "网络错误：" + response.code(), Toast.LENGTH_SHORT).show());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() ->
                            Toast.makeText(this, "注册异常：" + e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }).start();
        });
    }
}
